package com.cjm.one.common.handler;

import com.cjm.one.common.exception.GlobalException;
import com.cjm.one.common.result.Result;
import com.cjm.one.common.result.ResultCodeEnum;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.AccessDeniedException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail();
    }
    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public Result error(GlobalException e){
        log.error("全局异常信息 ex={}",e.getMessage());
        e.printStackTrace();
        return Result.build(null,e.getCode(),e.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result error(AccessDeniedException e) throws AccessDeniedException {
        return Result.build(null, ResultCodeEnum.USERNAME_FORMAT_ERROR);
    }
    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseBody
    public Result llegalArgumentException(Exception e) {
        e.printStackTrace();
        log.error("触发异常拦截: " + e.getMessage(), e);
        return Result.build(null, ResultCodeEnum.ARGUMENT_VALID_ERROR);
    }

    // controller传递参数校验异常处理
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
    public Result handleValidationException(Exception e) {
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        } else {
            bindingResult = ((BindException) e).getBindingResult();
        }

        // 获取第一个错误信息
        FieldError fieldError = bindingResult.getFieldError();
        String errorMsg = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";

        log.error("参数校验异常: {}", errorMsg);
        return Result.build(null, ResultCodeEnum.ARGUMENT_VALID_ERROR.getCode(), errorMsg);
    }

    @ExceptionHandler(FeignException.class)
    public Result<?> handleFeignException(FeignException e) {
        return Result.remoteFail(
                ResultCodeEnum.REMOTE_SERVICE_ERROR,
                "服务调用异常: " + e.contentUTF8()
        );
    }
}
